var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors=require('cors')
var expressJWT=require('express-jwt')

// 导入自定义模块

var DQJRouter = require('./routes/DQJ/index')
var HDDRouter = require('./routes/HDD/index')
var LPXRouter = require('./routes/LPX/index')
var XXKRouter = require('./routes/XXK/index')
var XXYRouter = require('./routes/XXY/index')
var ZHTRouter = require('./routes/ZHT/index')



// 创建服务器对象
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));//改变视图模板的默认路径
app.set('view engine', 'jade');//配置视图模板引擎


// 配置中间件
app.use(cors())//导入cors，解决跨域
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));//配置服务器的静态资源访问目录
app.use("/upload",express.static(path.join(__dirname,'upload')));
// 配置express-jwt 用与登录认证token
// app.use(
//   expressJWT({
//     secret:'123', //生成token的口令
//     algorithms:['HS256'],//加密方式
//   }).unless({
//     path:['/login'],//白名单
//   })
// )

// 配置路由模块化的中间件
app.use('/DQJ',DQJRouter)
app.use('/HDD',HDDRouter)
app.use('/LPX',LPXRouter)
app.use('/XXK',XXKRouter)
app.use('/XXY',XXYRouter)
app.use('/ZHT',ZHTRouter)

// 错误处理，
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误处理
// error handler
app.use(function(err, req, res, next) {
  console.log(err);
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // // render the error page
  // res.status(err.status || 500);
  // res.render('error');
});



// 服务端代码
const io = require('socket.io')(4000, {
  path: '/socket.chat',
  serveClient: true,
  transports: ['websocket', 'polling']
});

const connections = [];

io.sockets.on('connect', function (socket) {
  connections.push(socket);
  io.sockets.emit('userCount', { msg: connections.length })
  console.log('connected >>> [ %s ] online, [ %s ]', connections.length, new Date())

  socket.on('disconnect', function (data) {
      connections.splice(connections.indexOf(socket), 1);
      io.sockets.emit('userCount', { msg: connections.length});
      console.log(connections.length)
      console.log('disconnect >>> [ %s ] online', connections.length);
      delete socket;
  })

  socket.on('sendMessage', function (data) {
      console.log(data)
      io.sockets.emit('newMessage', { msg: data })
  })
})


console.log(`Server running on prot ${process.env.PORT || 4000}`);

module.exports = app;
